<template>
  <div class="box">
    <div class="querybox">
      <!-- <el-input v-model="query" placeholder="请输入查询内容" style="width: 200px; right: 10px;" /> -->
      <!-- <el-button type="primary" @click="ptestList">查询</el-button> -->
      <el-input
        v-model="filters.searchBy"
        placeholder="请输入查询内容"
        style="width: 200px; right: 10px;"
        @keyup.enter.native="ptestList(1)"
      />
      <el-button
        type="primary"
        @click="ptestList(1)"
      >查询</el-button>
      <el-button
        type="primary"
        @click="add"
      >新增</el-button>
    </div>
    <el-table
      :data="tableData"
      border
    >
      <el-table-column
        prop="title"
        label="标题"
      />
      <el-table-column
        prop="images"
        label="封面"
      >
        <template slot-scope="scope">
          <img
            :src="scope.row.images"
            alt=""
            width="80px"
          >
        </template>
      </el-table-column>
      <el-table-column
        label="链接地址"
      >
        <template slot-scope="scope">
          <a :href="scope.row.ref" target="_blank" style="text-decoration: underline;">链接地址</a>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="sales"
        label="销量"
      /> -->
      <el-table-column label="适用月龄">
        <template slot-scope="scope">
          <div>{{ `${scope.row.monthMin} ~ ${scope.row.monthMax}` }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="salesQuota"
        label="销量"
      />
      <el-table-column
        prop="salesQuota"
        label="销量限额"
      />
      <el-table-column
        prop="rebate"
        label="折扣"
      />
      <el-table-column
        prop="deleted"
        label="有效"
      />
      <el-table-column
        prop="comment"
        label="备注"
      /> -->
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          <div>{{ timeTranslateHMS(scope.row.created) }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="状态"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            @change="statusChange(scope.row)"
          />
        </template>
      </el-table-column> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="viewUser(scope.row.id, scope.index)"
          >查看</el-button>
          <!-- <el-button type="text" size="small" @click="updUser(scope.row, scope.index)">修改</el-button> -->
          <Del-tip
            type="text"
            size="small"
          >
            <el-button type="primary" size="mini" @click="delUser(scope.row.id)">确定</el-button>
          </Del-tip>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top: 10px;">
      <el-pagination
        :total="total"
        :current-page="filters.pageNum"
        :page-size="filters.pageSize"
        layout="total, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleSizeChange"
      />
    </el-row>

    <el-dialog
      :title="editType === 'add' ? '新增' : '查看'"
      :visible.sync="dialogFormVisible"
      :before-close="beforeClose"
    >

      <el-card class="box-card">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          :inline="true"
        >
          <el-form-item
            label="标题"
            prop="title"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.title"
              type="textarea"
              autocomplete="off"
              :autosize="{ minRows: 1, maxRows: 1}"
            />
          </el-form-item>
          <el-form-item
            label="封面"
            prop="images"
            :label-width="formLabelWidth"
          >
            <Upload
              v-model="form.images"
              style="width: 185px;"
              :img-url="form.images"
              @on-success="onSuccess"
            />
          </el-form-item>
          <el-form-item
            label="链接"
            prop="ref"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.ref"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item
            label="适用月龄"
            prop="monthMin"
            :label-width="formLabelWidth"
          >
            <el-input-number
              v-model="form.monthMin"
              :min="0"
              label="描述文字"
              size="mini"
            />
            <span> 至 </span>
            <el-input-number
              v-model="form.monthMax"
              :min="0"
              label="描述文字"
              size="mini"
            />
          </el-form-item>
          <el-form-item
            label="互动类型"
            prop="itemType"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="form.itemType"
              placeholder="请选择"
              style="width: 185px;"
            >
              <el-option
                v-for="item in itemTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="form.itemType === 0"
            label="答案类型"
            prop="answerType"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="form.answerType"
              placeholder="请选择"
              style="width: 185px;"
            >
              <el-option
                v-for="item in answerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="提示"
            prop="hint"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.hint"
              type="textarea"
              autocomplete="off"
              :autosize="{ minRows: 1, maxRows: 1}"
            />
          </el-form-item>
          <el-form-item
            label="创建时间"
            prop="created"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              v-model="form.created"
              type="date"
              placeholder="选择时间"
              disabled
              style="width: 185px;"
            />
          </el-form-item>
        </el-form>
      </el-card>
      <el-card v-if="form.itemType === 0 && form.answerType !== 3" class="box-card">
        <div
          slot="header"
          class="clearfix"
        >
          <span>答题卡</span>

          <div style="float: right;">
            <!-- <el-select
              v-model="optionType"
              placeholder="请选择"
              style="width: 185px;"
            >
              <el-option
                key="kending"
                label="肯定判断答案"
                :value="1"
              />
              <el-option
                key="fouding"
                label="否定判断答案"
                :value="2"
              />
            </el-select> -->
            <el-button-group>
              <el-button size="mini" @click="addOption(1)">肯定判断答案</el-button>
              <el-button size="mini" @click="addOption(2)">否定判断答案</el-button>
              <el-button size="mini" @click="addOption(0)">新增</el-button>
            </el-button-group>
            <!-- <el-button
              type="text"
              icon="el-icon-plus"
              size="mini"
              @click="addOption"
            /> -->
          </div>
        </div>
        <el-table
          :data="form.options"
          border
        >
          <el-table-column label="答案">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.choice"
                autocomplete="off"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="images"
            label="图片"
          >
            <template slot-scope="scope">
              <Upload
                v-model="scope.row.image"
                style="width: 185px;"
                :img-url="scope.row.image"
                @on-success="imageOnSuccess"
              />
            </template>
          </el-table-column> -->
          <el-table-column label="是否正确答案">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.answer"
                active-text="是"
                inactive-text="否"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="50px">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="delOption(scope.row, scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="姓名" prop="username" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="form.mobile" autocomplete="off" />
        </el-form-item>
      </el-form> -->
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button
          type="primary"
          @click="closeDialogForm('form')"
        >确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { ptestList, ptestInfo, ptestEdit, ptestDelete } from '@/api/knowledge'
import { bizorg_trans } from '@/api/org'
import { timeTranslateHMS } from '@/utils/formatdate'
import Upload from '@/components/Upload'
export default {
  name: 'Documentation',
  components: {
    Upload
  },
  data() {
    return {
      timeTranslateHMS,
      filters: {
        mobile: '',
        username: '',
        pageNum: 1,
        pageSize: 10,
        searchBy: ''
      },
      form: {
        title: '',
        images: '',
        dealerPhone: '',
        ref: '',
        monthMin: '',
        monthMax: '',
        itemType: '',
        answerType: '',
        hint: '',
        created: '',
        options: []
      },
      optionType: 1,
      total: 0,
      rules: {
        title: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        images: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        dealerPhone: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        ref: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        monthMin: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        monthMax: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        itemType: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        answerType: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        created: [
          { required: false, message: '不能为空', trigger: 'blur' }
        ]
      },
      tableData: [],
      formLabelWidth: '120px',
      dialogFormVisible: false,
      query: '',
      editType: null,
      itemTypeOptions: [
        {
          value: 0,
          label: '问答'
        },
        {
          value: 1,
          label: '知识点'
        }
      ],
      answerTypeOptions: [
        {
          value: 1,
          label: '单选'
        },
        {
          value: 2,
          label: '多选'
        },
        {
          value: 3,
          label: '文本'
        },
        {
          value: 4,
          label: '判断'
        }
      ]
    }
  },
  mounted() {
    this.ptestList()
  },
  methods: {
    addOption(type) {
      switch (type) {
        case 1:
        case 2:
          this.form.options = [
            {
              choice: '正确',
              image: '',
              answer: type === 1
            },
            {
              choice: '错误',
              image: '',
              answer: type === 2
            }
          ]
          break
        case 0:
          this.form.options.push({
            choice: '',
            image: '',
            answer: false
          })
          break
      }
    },
    bizOrgChange(orgId) {
      orgId = '4028808a748b6e4f01748b71b6bf0002'
      bizorg_trans({ orgId }).then((res) => {
      })
    },
    // dialog关闭事件
    beforeClose() {
      this.form.options = []
      this.resetForm('form')
    },
    // logo上传成功监听
    onSuccess(res) {
      this.form.images = res
    },
    // logo上传成功监听
    imageOnSuccess(res, diffData) {
      const options = this.form.options
      for (let i = 0; i < options.length; i++) {
        if (options[i].image === diffData) {
          options[i].image = res
          options.splice(i, 1, { ...options[i] })
        }
      }
    },
    // 新增操作
    add() {
      this.editType = 'add'
      this.dialogFormVisible = true
    },
    // 分页切换监听
    handleSizeChange(pageNum) {
      this.filters.pageNum = pageNum
      this.ptestList()
    },
    // 用户列表
    ptestList(num) {
      if (num === 1) this.filters.pageNum = 1 // 查询时，分页器数字重置为1
      const pageNum = (num || this.filters.pageNum) - 1
      ptestList({ ...this.filters, pageNum }).then(res => {
        const result = res.data
        this.tableData = result.content
        this.total = result.totalElements
      }).catch(err => {
        console.log(err)
      })
    },
    // 删除用户
    delUser(id) {
      this.editType = 'delete'
      // this.tableData.splice(row, 1)
      // this.$message({
      //   message: '删除成功！',
      //   type: 'success'
      // })
      ptestDelete({ itemId: id }).then((res) => {
        this.$message({
          message: '删除成功！',
          type: 'success'
        })
        this.ptestList()
      })
    },
    // 删除用户
    delOption(row, index) {
      this.form.options.splice(index, 1)
    },
    // 修改用户
    updUser(row, index) {
      this.editType = 'update'
      this.dialogFormVisible = true
    },
    // 查看用户
    viewUser(id) {
      this.editType = 'view'
      this.dialogFormVisible = true
      this.ptestInfo(id)
    },
    // 用户详情
    ptestInfo(id) {
      ptestInfo({ userId: id }).then(res => {
        // res.data.org.logo = 'https://dss1.baidu.com/70cFfyinKgQFm2e88IuM_a/forum/pic/item/bd315c6034a85edf3d432b7d44540923dc5475a5.jpg'
        this.form = res.data
        // let result = res.data;
        // this.tableData = result.users;
      }).catch(err => {
        console.log(err)
      })
    },
    // 弹窗关闭触发函数
    closeDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ptestEdit(formName)
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    // 新增用户
    ptestEdit(formName) {
      const obj = { ...this.form }
      if (obj.itemType === 1 || obj.answerType === 3) {
        obj.options = []
      }
      obj.created = timeTranslateHMS(obj.created, null, '/')
      const form = this.$transToFormData(obj)
      ptestEdit(form).then((res) => {
        this.$message({
          message: '修改成功！',
          type: 'success'
        })
        this.ptestList()
        this.resetForm(formName)
        // this.dialogFormVisible = false
      })
    },
    statusChange(row) {
      // {id: row.id, status: row.status}
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  margin: 20px 30px;
  .form {
    margin-top: 50px;
  }
  .querybox {
    text-align: right;
    margin-bottom: 20px;
  }
}
.box-card {
  margin-bottom: 15px;
}
</style>
